// 封装获取元素函数
let $ = (el)=> document.querySelector(el);
let gets = (el) => [...document.querySelectorAll(el)];
let header = $('.header'),
    inp = $('input'),
    textArea = $('textarea')
    box = $('.box');
$('.num').innerHTML = $('.con').children.length;
// 给留言框设置input
textArea.addEventListener('input',(e) => {
    let max = textArea.getAttribute('maxlength');
    $('.countNum').innerHTML = max - textArea.value.trim().length;
})
// 给box设置点击事件
box.addEventListener('click',(e) => {
    let target = e.target;
    // 给图片点击添加高亮
    if(target.nodeName === 'IMG' && target.parentNode.parentNode.classList.contains('header')){
        let span = $('.active');
        console.log(target.getAttribute('src'))
        span && span.classList.remove('active')
        target.parentNode.classList.add('active')
    // 给广播添加点击事件并将内容添加到con中
    }else if(target.nodeName === 'BUTTON'){
        if(inp.value.trim() === '') return alert('请输入用户名');
        if($('.active') === null) return alert('请选择您的头像');
        if(textArea.value.trim() === '') return alert('请输入留言内容');
        let dl = document.createElement('dl');
        src = $('.active').firstElementChild.getAttribute('src');
        dl.innerHTML = ` <dt><img src="${src}" alt=""></dt>
                        <dd>
                            <h4><a href="#">${inp.value}:</a> ${textArea.value}</h4>
                            <p>${data()}   发布日期 <span class="del">删除</span></p>
                        </dd>`
        $('.con').appendChild(dl);
        // 清空文本框内容和高亮
        inp.value = '';
        textArea.value = '';
        $('.active').classList.remove('active');
        $('.countNum').innerHTML = '40'
        $('.num').innerHTML = $('.con').children.length;
    // 点击del删除该条内容
    }else if(target.nodeName === 'SPAN' && target.classList.contains('del')){
        target.parentNode.parentNode.parentNode.remove();
        $('.num').innerHTML = $('.con').children.length;
    // 将con内容展开
    }else if(target.nodeName === 'SPAN' && target.classList.contains('tit')){
        $('.con').classList.add('show');
    // 将con内容收起
    }else if(target.nodeName === 'SPAN' && target.classList.contains('pl')){
        $('.con').classList.remove('show')
    }
});
// 封装留言日期函数
function data(){
    let date = new Date(),
        month = zero(date.getMonth()+1),
        day = zero(date.getDate()),
        hour = zero(date.getHours()),
        minute = zero(date.getMinutes());
    return `${month}月${day}日&nbsp${hour}:${minute}`
}

// 封装补零函数
function zero(num){
    return num<10? '0'+ num : num
}